import orderApi from '@/api/orderApi'
import type { IModalDetail } from '@/types/modal'
import type { OrderItem } from '@/types/orderType'
import { Modal } from 'antd'
import { useImperativeHandle, useState } from 'react'
import { flushSync } from 'react-dom'

const PolyLine = (props: IModalDetail) => {
  const [visible, setVisible] = useState(false)
  const [trackAni, setTrackAni] = useState<{ cancel: () => void }>()
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  const open = async (orderId: string) => {
    flushSync(() => {
      setVisible(true)
    })
    const res = await orderApi.getOrderDetail(orderId)
    renderMap(res)
  }
  const renderMap = (res: OrderItem) => {
    const map = new window.BMapGL.Map('polyLine')
    map.centerAndZoom(res.cityName, 17) // 初
    const point: any[] = []
    res.route.forEach(item => {
      point.push(new window.BMapGL.Point(item.lng, item.lat))
    })
    const pl = new window.BMapGL.Polyline(point)
    const trackAni = new window.BMapGLLib.TrackAnimation(map, pl, {
      overallView: true,
      tilt: 30,
      duration: 20000,
      delay: 300
    })
    setTimeout(() => {
      trackAni.start()
      setTrackAni(trackAni)
    }, 2000)
  }
  const handleCancel = () => {
    setVisible(false)
    trackAni?.cancel()
  }
  return (
    <Modal title='轨迹' width={800} open={visible} footer={false} onCancel={handleCancel}>
      <div id='polyLine' style={{ height: 500 }}></div>
    </Modal>
  )
}

export default PolyLine
